package com.itmumu.miniwechat.chat.websocket;


import cn.hutool.system.UserInfo;
import com.itmumu.miniwechat.common.utils.RedisComponent;
import com.itmumu.miniwechat.user.domain.enums.UserContactTypeEnum;
import com.itmumu.miniwechat.user.domain.po.User;
import com.itmumu.miniwechat.user.service.UserService;
import io.netty.channel.Channel;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.AttributeKey;
import io.netty.util.concurrent.GlobalEventExecutor;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.time.Instant;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

@Component("ChannelContextUtil")
@Slf4j
public class ChannelContextUtil {

    @Resource
    private RedisComponent redisComponent;

    @Resource
    private UserService userService;

    public static final ConcurrentMap<Integer, Channel> USER_CONTEXT_MAP = new ConcurrentHashMap();

    public static final ConcurrentMap<Integer, ChannelGroup> GROUP_CONTEXT_MAP = new ConcurrentHashMap();

    /**
     * 加入通道
     *
     * @param userId
     * @param channel
     */
    public void addContext(Integer userId, Channel channel) {
        String channelId = channel.id().toString();
        log.info("加入通道:userId={},channelId={}", userId, channelId);
        AttributeKey attributeKey = null;
        if (!AttributeKey.exists(channelId)) {
            attributeKey = AttributeKey.newInstance(channel.id().toString());
        } else {
            attributeKey = AttributeKey.valueOf(channel.id().toString());
        }

        channel.attr(attributeKey).set(userId);
        USER_CONTEXT_MAP.put(userId, channel);
        redisComponent.saveUserHeartBeat(userId);

        // TODO 如果是群组，需要将用户加入群组

        // 获取用户联系人
        List<Map> contactIds =  redisComponent.getUserContactList(userId);
        log.info("用户联系人:{}", contactIds);
        for (Map contact : contactIds) {
            if (contact.get("contactId") != null && contact.get("contactType") == UserContactTypeEnum.GROUP) {
                add2Group((Integer) contact.get("contactId"), channel);
            }
        }

        // 更新用户最近登录时间
        User userInfo = new User();
        userInfo.setUid(userId);
        userInfo.setLastLoginTime(Instant.now().getEpochSecond());
        userService.save(userInfo);

        //给用户发送一些消息
        //获取用户最后离线时间

    }

    private void add2Group(Integer groupId, Channel context) {
        ChannelGroup group = GROUP_CONTEXT_MAP.get(groupId);
        if (group == null) {
            group = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
            GROUP_CONTEXT_MAP.put(groupId, group);
        }
        if (context == null) {
            return;
        }
        group.add(context);
    }
}
